package com.polaris.live.ui.message.fragment

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.polaris.live.R
import com.polaris.live.adapter.MainMessageSingleAdapter
import com.polaris.live.common.cacha.CacheUtil
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.constant.UserConst
import com.polaris.live.databinding.FragmentMainMessageBinding
import com.polaris.live.im.manager.ImSessionManager
import com.polaris.live.im.sfs.COMMAND_SYSTEM_MESSAGE
import com.polaris.live.interface_bag.PAGListener
import com.polaris.live.utils.PushNoticeUtils
import com.polaris.live.utils.StartMessageProxy
import com.polaris.live.utils.fragment.attachFragment
import com.polaris.live.utils.interfaces.OnAutoRefreshListener
import com.polaris.live.viewmodel.message.MainMessageViewModel
import org.libpag.PAGImageView
import java.lang.Math.abs

/**
 * 消息
 *
 * @author Created by 半仙 on 2023/8/14/014 15:33
 */
class MainMessageFragment : BaseVbFragment<MainMessageViewModel, FragmentMainMessageBinding>(),
    OnAutoRefreshListener {

    private var mPosition = -1

    private val mTitleAdapter by lazy {
        MainMessageSingleAdapter()
    }

    private val mFragment by lazy {
        childFragmentManager.attachFragment(R.id.fl_fragment) {
            MessageSessionFragment().apply {
                arguments = bundleOf("sessionCommand" to COMMAND_SYSTEM_MESSAGE)
            }
        }
    }

    private var mIsClosedNoticePrompt = false

    private var mIsExpand = true

    override fun initView(savedInstanceState: Bundle?) {
        mFragment

        initView()
        initListener()
        initObserver()
        mBinding.rechargeAc.registerObserve(lifecycle, mViewModel)
    }

    private fun initView() {

        mBinding.appBarLayout.addOnOffsetChangedListener { appBarLayout, verticalOffset ->
            if (abs(verticalOffset) - appBarLayout.totalScrollRange == 0) {
                if (!mIsExpand) {
                    return@addOnOffsetChangedListener
                }
                mIsExpand = false
                // Collapsed (滚动到顶部)
                var following = 0
                var recommend = 0
                mTitleAdapter.data.forEach {
                    if (it.follow) {
                        following++
                    } else {
                        recommend++
                    }
                }
                if (following == 0 || recommend == 0) {
                    mBinding.occupy.visibility = View.GONE
                } else {
                    mBinding.occupy.visibility = View.VISIBLE
                }
                if (following > 0) {
                    mBinding.tvFollowing.text = "$following"
                    mBinding.tvFollowing.visibility = View.VISIBLE
                    mBinding.tvF.visibility = View.VISIBLE
                } else {
                    mBinding.tvFollowing.visibility = View.GONE
                    mBinding.tvF.visibility = View.GONE
                }
                if (recommend > 0) {
                    mBinding.tvRecommend.text = "$recommend"
                    mBinding.tvRecommend.visibility = View.VISIBLE
                    mBinding.tvR.visibility = View.VISIBLE
                } else {
                    mBinding.tvRecommend.visibility = View.GONE
                    mBinding.tvR.visibility = View.GONE
                }
                mBinding.hiddenToolbar.visibility = View.VISIBLE
                mBinding.recycler.visibility = View.INVISIBLE
            } else {
                mIsExpand = true
                // Not collapsed (未滚动到顶部)
                mBinding.hiddenToolbar.visibility = View.GONE
                mBinding.recycler.visibility = View.VISIBLE
            }
        }


        mBinding.recycler.apply {
            layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
            adapter = mTitleAdapter
            itemAnimator = null
        }
    }

    private fun initObserver() {
        mViewModel.singleLiveData.observe(this) { resultState ->
            parseState(resultState, {
                if (it.isNotEmpty()) {
                    mBinding.appBarLayout.visibility = View.VISIBLE
                    if (mBinding.appBarLayout.parent == null) {
                        mBinding.coordinatorlayout.addView(mBinding.appBarLayout)
                    }
                } else {
                    mBinding.appBarLayout.visibility = View.GONE
                    if (mBinding.appBarLayout.parent != null) {
                        mBinding.coordinatorlayout.removeView(mBinding.appBarLayout)
                    }
                }
                mPosition = -1
                mTitleAdapter.setList(it)
            })
        }
        mViewModel.greetMessageLiveData.observe(this) {
            ImSessionManager.convertGreetMessageTimeoutToStranger()
            mFragment.greetMessageScan()
        }

        //关注
        mViewModel.followerLiveData.observe(this) { resultState ->
            parseState(resultState, {
                if (mPosition != -1) {
                    val ivFocus =
                        mTitleAdapter.getViewByPosition(mPosition, R.id.iv_focus) as? PAGImageView
                    ivFocus?.apply {
                        addListener(object : PAGListener {
                            override fun onAnimationEnd(p0: PAGImageView?) {
                                mTitleAdapter.data.getOrNull(mPosition)?.follow = true
                                mTitleAdapter.notifyItemChanged(mPosition)
                            }
                        })
                        play()
                    }
                }
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }
    }

    private fun initListener() {
        mBinding.hiddenToolbar.setOnSingleClickListener {
            if (!mIsExpand) {
                mBinding.appBarLayout.setExpanded(true)
                mFragment.scrollToTop()
            }
        }
        mTitleAdapter.setOnItemClickListener { _, _, position ->
            val item = mTitleAdapter.data[position]

            StartMessageProxy.gotoMessage(
                requireActivity(),
                UserConst.From.SINGLE,
                item.base
            )
        }
        mTitleAdapter.setOnItemChildClickListener { _, _, position ->
            mPosition = position
            mViewModel.addFollower(mTitleAdapter.data[position].base.userId)
        }
        mBinding.llMessageNoticePrompt.setOnSingleClickListener {
            permissionNotice()
        }
        mBinding.ivNoticeClose.setOnSingleClickListener {
            mIsClosedNoticePrompt = true
            hideNoticePrompt()
        }
    }

    override fun initData() {
        mViewModel.launchGreetMessage()
//TODO 暂时隐藏，过两个版本确定不要后再删除这里的代码
//        mViewModel.singleTop()
    }

    override fun onResume() {
        super.onResume()
        if (!isHidden) {
            resumeCheckNoticePermission()
            ImSessionManager.clearStrangerSessionFromOneDayAgo()
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        withLoaded {
            if (!hidden) {
                resumeCheckNoticePermission()
                ImSessionManager.clearStrangerSessionFromOneDayAgo()
            }
        }
    }

    private fun resumeCheckNoticePermission() {
        if (mIsClosedNoticePrompt) {
            return
        }
        if (!CacheUtil.isFirstApplyNoticePermission()) {
            permissionNotice()
            CacheUtil.setApplyNoticePermission()
        } else {
            if (PushNoticeUtils.hasNoticePermission(requireContext())) {
                hideNoticePrompt()
            } else {
                if (PushNoticeUtils.needNoticePermission()) {
                    showNoticePrompt(false)
                } else {
                    hideNoticePrompt()
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == PushNoticeUtils.REQUEST_CODE_NOTIFICATION) {
            if (PushNoticeUtils.hasNoticePermission(requireContext())) {
                hideNoticePrompt()
            }
        }
    }

    private fun permissionNotice() {
        PushNoticeUtils.permissionNotice(requireActivity(), {
            hideNoticePrompt()
        }, {
            showNoticePrompt()
        })
    }

    private fun showNoticePrompt(needCheck: Boolean = true) {
        //有一个选用是true就需要显示
        if (!needCheck || PushNoticeUtils.needNoticePermission()) {
            mBinding.llMessageNoticePrompt.visibility = View.VISIBLE
        }
    }

    private fun hideNoticePrompt() {
        if (!isCreated()) {
            return
        }
        mBinding.llMessageNoticePrompt.visibility = View.GONE
    }

    override fun onAutoRefresh() {
        if (isCreated()) {
            mFragment.onAutoRefresh()
        }
    }
}